package com.example.springstudy.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.dao.req.SkuCatReq;
import com.example.springstudy.dao.dto.SkuDto;
import com.example.springstudy.dao.dto.SkuExportDto;
import com.example.springstudy.entity.Sku;
import com.example.springstudy.listener.SkuImportListener;
import com.example.springstudy.service.SkuService;
import com.example.springstudy.utils.ExcelUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/sku")
public class SkuController {
    @Autowired
    SkuService skuService;

    @GetMapping("/list")
    public Result<?> getList(
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size,
            @RequestParam(required = false, defaultValue = "") String keyword
    ){
        return Result.success(skuService.getSkuList(page, size, keyword));
    }

    @SaveLog("修改商品")
    @PostMapping("/addOrUpdate")
    public Result<?> add(@RequestBody Sku sku){
        try{
            Assert.hasText(sku.getName(), "name is empty");
            Assert.hasText(sku.getCode(), "code is empty");
            Assert.notNull(sku.getPrice(), "price is empty");
            if(sku.getId()==null || sku.getId()==0){
                return Result.success(skuService.addSku(sku));
            } else {
                return Result.success(skuService.updateSku(sku));
            }
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    @SaveLog("导入商品")
    @PostMapping("/import")
    public Result<?> importSku(MultipartFile file) throws IOException {
        log.info("file: {}", JSONUtil.toJsonStr(file));
        SkuImportListener listener = new SkuImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), SkuDto.class, listener);
        return Result.success(msg);
    }

    @SaveLog("导入商品")
    @GetMapping("/export")
    public void exportUsers(@RequestParam List<Integer> ids, HttpServletResponse response) throws IOException {
        String fileName = "商品列表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SkuExportDto> list = skuService.findExportList(ids);
        log.info("list: {}", list);

        EasyExcel.write(response.getOutputStream(), SkuExportDto.class).sheet("商品列表")
                .doWrite(list);
    }

    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "商品导入模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @SaveLog("修改商品类型")
    @PostMapping("/updateSkuCategory")
    public Result<?> updateSkuCategory(@RequestBody SkuCatReq req){
        try{
            Assert.notEmpty(req.getSkuIds(), "skuIds is empty");
            Assert.isTrue(req.getCategoryId()!=0, "categoryId is empty");
            return Result.success(skuService.updateSkuCategory(req.getCategoryId(), req.getSkuIds()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.failed(e.getMessage());
        }

    }
}
